package com.lfd.hashmap;

import java.util.concurrent.*;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.hashmap
 * @文件名: MyThreadPoolExecutor
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/13 17:37
 * @描述：Java线程池中submit()和execute()方法有什么区别？ (1) 两个方法都可以向线程池提交任务；
 * (2) execute只能提交Runnable，无返回值；
 * (3) submit既可以提交Runnable，返回值为null，也可以提交Callable，返回值Future；
 * (4) execute()方法定义在Executor接口中；
 * (5) submit()方法定义在ExecutorService接口中；
 * (6) execute执行任务时遇到异常会直接抛出；
 * (7) submit执行任务时遇到异常不会直接抛出，只有在调用Future的get()方法获取返回值时，才会抛出异常；
 */
public class MyThreadPoolExecutor {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(5), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        }, new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolExecutor.execute(() -> {
            System.out.println("Thread.currentThread().getName():" + Thread.currentThread().getName());
        });
        Future<Object> submit = threadPoolExecutor.submit(new Callable<Object>() {
            @Override
            public Long call() throws Exception {
                long l = System.currentTimeMillis();
                return l;
            }
        });
        System.out.println("submit->"+submit.get());
        Future<Object> submit1 = threadPoolExecutor.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                int i =1/0;
                return "11111";
            }
        });
//        System.out.println("submit1->"+submit1.get());
//        threadPoolExecutor.execute(new Runnable() {
//            @Override
//            public void run() {
//                int i =1/0;
//                System.out.println("Thread.currentThread().getName():" + Thread.currentThread().getName());
//            }
//        });
    }
}
